package com.wl156.activities.find;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.activities.find.FindCarMessageResult.FindTask;
import com.wl156.adapters.CheckableAdapter;
import com.wl156.adapters.TruckAdapter;
import com.wl156.model.Certificate;
import com.wl156.model.WebServiceClient;

public abstract class FindResultBase extends ListActivity implements
		OnClickListener {

	public static final String TAG = null;
	protected WebServiceClient mWebServiceClient;
	protected Certificate mCertificate;
	protected int countPerPage;

	protected int mCurrentPageIndex = -1;
	protected SoapObject mItems;

	private int mLastSavedTotalCount = -1;
	private boolean isListenedScroll = true;

	protected View mFooterView;
	protected ProgressBar mFooterProgress;
	protected TextView mFooterText;

	protected ViewStub mHeaderStub;

	protected Button mReturn;
	protected Button mSendMessage;
	protected Button mCitySearch;
	protected Button mShengneiduantu;
	protected Button mProvinceSearch;

	protected String startLocationLv1;
	protected String startLocationLv2;
	protected String startLocationLv3;

	protected BaseAdapter mAdapter;
	protected int type;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_find_result);

		try {
			mFooterView = getLayoutInflater().inflate(R.layout.item_loading,
					null);
			mFooterProgress = (ProgressBar) mFooterView
					.findViewById(R.id.progress);
			mFooterText = (TextView) mFooterView.findViewById(R.id.text);
			getListView().addFooterView(mFooterView, null, false);
			setListAdapter(new TruckAdapter(this, null));

			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				type = extras.getInt("type", FindTask.CITY);
				startLocationLv1 = extras.getString("startLocationLv1");
				startLocationLv2 = extras.getString("startLocationLv2");
				startLocationLv3 = extras.getString("startLocationLv3");
			}

			mReturn = (Button) findViewById(R.id.return_search);
			mReturn.setOnClickListener(this);
			mSendMessage = (Button) findViewById(R.id.send_message);
			mSendMessage.setOnClickListener(this);
			mCitySearch = (Button) findViewById(R.id.city_search);
			mCitySearch.setOnClickListener(this);
			mCitySearch.setText("附近" + getFindName());
			mShengneiduantu = (Button) findViewById(R.id.shengneiduantu);
			mShengneiduantu.setOnClickListener(this);

			if (extras != null) {
				String OristartLocationLv2 = extras
						.getString("OristartLocationLv2");
				if (OristartLocationLv2 != null) {
					mCitySearch.setTag(OristartLocationLv2);
				} else {
					mCitySearch.setTag(startLocationLv2);
				}
			}
			mProvinceSearch = (Button) findViewById(R.id.province_search);
			mProvinceSearch.setOnClickListener(this);
			mProvinceSearch.setText("所有" + getFindName());

			mWebServiceClient = new WebServiceClient(this);
			mCertificate = ((MyApp) getApplication()).getCertificateFromXml();
			countPerPage = ((MyApp) getApplication()).getCountPerPage();

			getListView().setOnScrollListener(new OnScrollListener() {
				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					if (isListenedScroll
							&& (firstVisibleItem + visibleItemCount == totalItemCount)
							&& firstVisibleItem > 0 && visibleItemCount > 0
							&& totalItemCount > 0) {
						if (totalItemCount != mLastSavedTotalCount) {
							mLastSavedTotalCount = totalItemCount;
							onLastItemVisible();
						}
					}
				}
			});

			getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		} catch (Exception e) {
		}
	}

	public void hideBottomButtons() {
		mReturn.setVisibility(View.GONE);
		mSendMessage.setVisibility(View.GONE);
		mCitySearch.setVisibility(View.GONE);
		mProvinceSearch.setVisibility(View.GONE);
		mShengneiduantu.setVisibility(View.GONE);
	}

	@Override
	public void onContentChanged() {
		super.onContentChanged();

		mHeaderStub = (ViewStub) findViewById(R.id.header_stub);
	}

	protected void setListenScroll(boolean isListened) {
		isListenedScroll = isListened;
	}

	protected void onLastItemVisible() {
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.return_search: {
			Class activity = getFindActivity();
			Intent i = new Intent(this, activity);
			i.putExtra("type", FindTaskBase.DETAIL);
			i.putExtra("isReturn", true);
			i.putExtras(getIntent());
			startActivity(i);
		}
			break;
		case R.id.send_message: {
			try {
				List<Integer> checkedList = ((CheckableAdapter) (((HeaderViewListAdapter) getListView()
						.getAdapter()).getWrappedAdapter())).getCheckedList();

				StringBuilder numbers = new StringBuilder();
				int count = getListView().getAdapter().getCount();
				for (int i = 0; i < count; i++) {
					if (checkedList.contains(i)) {
						SoapObject so = (SoapObject) getListView().getAdapter()
								.getItem(i);
						String phone = so.getProperty(getPhoneIndex())
								.toString();
						numbers.append(phone);
						numbers.append(";");
					}
				}
				Uri uri = Uri.parse("smsto:" + numbers.toString());
				Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
				intent.putExtra("sms_body", "The SMS text");
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
			break;
		case R.id.province_search: {
			Intent i = new Intent(this, getFindResultActivity());
			i.putExtras(getIntent());
			i.putExtra("type", FindTask.PROVINCE);
			// String capital = Database.getInstance(this).getProvinceCapital(
			// startLocationLv1);
			i.putExtra("startLocationLv2", "");
			i.putExtra("endLocationLv1", "");
			i.putExtra("OristartLocationLv2", mCitySearch.getTag().toString());
			startActivity(i);
			finish();
		}
			break;
		case R.id.shengneiduantu: {
			Intent i = new Intent(this, getFindResultActivity());
			i.putExtras(getIntent());
			i.putExtra("type", FindTask.DUANTU);
			i.putExtra("startLocationLv2", "");
			i.putExtra("endLocationLv1", startLocationLv1);
			i.putExtra("OristartLocationLv2", mCitySearch.getTag().toString());
			startActivity(i);
			finish();
		}
			break;
		case R.id.city_search: {
			Intent i = new Intent(this, getFindResultActivity());
			i.putExtras(getIntent());
			i.putExtra("type", FindTask.CITY);
			i.putExtra("endLocationLv1", "");
			i.putExtra("startLocationLv2", mCitySearch.getTag().toString());
			startActivity(i);
			finish();
		}
			break;
		default:
			break;
		}
	}

	protected abstract String getFindName();

	protected abstract Class getFindResultActivity();

	protected abstract Class getFindActivity();

	protected abstract int getPhoneIndex();

	protected abstract Class getAdapter();

	public abstract class FindTaskBase extends AsyncTask<Void, Void, Object> {
		public static final int PROVINCE = 0;
		public static final int CITY = 1;
		public static final int DETAIL = 2;
		public static final int OTHER = 3;
		public static final int DUANTU = 4;

		public int type;

		public FindTaskBase(int type) {
			this.type = type;
			mCurrentPageIndex++;
		}

		public FindTaskBase() {
			this(CITY);
		}

		protected ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			switch (type) {
			case PROVINCE:
				setTitle(String.format("%s(全部)", getFindName(),
						startLocationLv1, startLocationLv2));
				break;
			case CITY:
				setTitle(String.format("%s(附近)", getFindName(),
						startLocationLv1, startLocationLv2));
				break;
			case DETAIL:
				setTitle(String.format("%s(搜索)", getFindName(),
						startLocationLv1, startLocationLv2));
				break;
			case DUANTU:
				setTitle(String.format("%s(短途)", getFindName(),
						startLocationLv1, startLocationLv2));
				break;
			case OTHER:
				break;
			}
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);

			try {
				Log.d(TAG, "result: " + result);
				if (result == null) {
					Toast.makeText(FindResultBase.this, "没有相应数据",
							Toast.LENGTH_LONG).show();
					mFooterView.setVisibility(View.GONE);
					return;
				}

				if (result instanceof SoapObject) {
					SoapObject so = (SoapObject) result;
					if (so.getPropertyCount() == 0) {
						setListenScroll(false);
						mFooterProgress.setVisibility(View.GONE);
						getListView().removeFooterView(mFooterView);
						mFooterText.setText("");
					} else if (so.getPropertyCount() == 1
							&& ((SoapObject) so.getProperty(0))
									.getPropertyCount() == 0) {
						SoapObject so1 = (SoapObject) so.getProperty(0);
						if (so1.getPropertyCount() == 0) {
							setListenScroll(false);
							mFooterProgress.setVisibility(View.GONE);
							getListView().removeFooterView(mFooterView);
							mFooterText.setText("");
						}
					} else {
						Log.d(TAG, "findresultbase adapter else");
						if (mAdapter == null) {
							mItems = so;
							try {
								mAdapter = (BaseAdapter) getAdapter()
										.getDeclaredConstructors()[0]
										.newInstance(FindResultBase.this,
												mItems);
							} catch (IllegalArgumentException e) {
								e.printStackTrace();
							} catch (SecurityException e) {
								e.printStackTrace();
							} catch (InstantiationException e) {
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							} catch (InvocationTargetException e) {
								e.printStackTrace();
							}
							getListView().setAdapter(mAdapter);
						} else {
							for (int i = 0; i < so.getPropertyCount(); i++) {
								mItems.addSoapObject((SoapObject) so
										.getProperty(i));
							}
							mAdapter.notifyDataSetChanged();
						}

						mFooterProgress.setVisibility(View.GONE);
						getListView().removeFooterView(mFooterView);
						mFooterText.setText("");
					}
				} else {
					Toast.makeText(FindResultBase.this, "网络异常，请稍候重试",
							Toast.LENGTH_LONG).show();
					onLoadFailed();
				}
			} catch (Exception e) {
				Toast.makeText(FindResultBase.this, "网络异常，请稍候重试",
						Toast.LENGTH_LONG).show();
			}
		}

		protected void onLoadFailed() {
		}
	}
}
